<template>
  <div ref="map" class="map">
    <div style="position: absolute; top: 15px; left: 80px; z-index: 99">
      <button @click="showLayer">显示testpoint</button>
      <button @click="hideLayer">隐藏testpoint</button>
      <button @click="showLayer2">显示testpoint2</button>
      <button @click="hideLayer2">隐藏testpoint2</button>
      <button @click="hightlightByDistrictName('黄浦区')">
        hightlightByDistrictName
      </button>
      <button @click="initDistrictClusterLayer">点位聚合图</button>
      <button @click="showFeatureLayer">带标注的撒点</button>
    </div>
  </div>
</template>

<script>
import jsapiUtil from "../utils/jsapi";
import tokenUtil from "../utils/token";
import testpoint from "../data/testpoint";
import testpoint2 from "../data/testpoint2";
import district from "../data/district";
import sfqDistrict from "../data/sfqDistrict";
import subway from "../data/subway";
import districtCenter from "../data/districtCenter";
import townCenter from "../data/townCenter";

export default {
  name: "MyMap",
  props: {
    msg: String,
  },
  data() {
    return {
      map: {},
      layers: {},
    };
  },
  async mounted() {
    const [
      Map,
      Extent,
      IdentityManager,
      GraphicsLayer,
      Graphic,
      Point,
      SimpleMarkerSymbol,
      Color,
      InfoTemplate,
      FeatureLayer,
      ArcGISDynamicMapServiceLayer,
      ArcGISTiledMapServiceLayer,
    ] = await jsapiUtil.load([
      "esri/map",
      "esri/geometry/Extent",
      "esri/IdentityManager",
      "esri/layers/GraphicsLayer",
      "esri/graphic",
      "esri/geometry/Point",
      "esri/symbols/SimpleMarkerSymbol",
      "esri/Color",
      "esri/InfoTemplate",
      "esri/layers/FeatureLayer",
      "esri/layers/ArcGISDynamicMapServiceLayer",
      "esri/layers/ArcGISTiledMapServiceLayer",
    ]);

    //获取并注册地图服务的token
    const {
      data: { token },
    } = await tokenUtil.getToken();

    IdentityManager.registerToken({
      server: "http://10.87.94.143/OneMapServer/rest/services",
      token: token,
    });

    // window.shanghaiSpatialRef =
    //   'PROJCS["shanghaicity",GEOGCS["GCS_Beijing_1954",DATUM["D_Beijing_1954",SPHEROID["Krasovsky_1940",6378245.0,298.3]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",-3457147.81],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",121.2751921],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]';

    window.fullExtent = new Extent({
      xmin: -400000,
      ymin: -150000,
      xmax: 240000,
      ymax: 140000,
      spatialReference: {
        wkt: 'PROJCS["shanghaicity",GEOGCS["GCS_Beijing_1954",DATUM["D_Beijing_1954",SPHEROID["Krasovsky_1940",6378245.0,298.3]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",-3457147.81],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",121.2751921],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]',
      },
    });
    window.initExtent = new Extent({
      xmin: -60000,
      ymin: -36000,
      xmax: 13100,
      ymax: 10000,
      spatialReference: {
        wkt: 'PROJCS["shanghaicity",GEOGCS["GCS_Beijing_1954",DATUM["D_Beijing_1954",SPHEROID["Krasovsky_1940",6378245.0,298.3]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",-3457147.81],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",121.2751921],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]',
      },
    });

    //初始化map对象
    const map = new Map(this.$refs.map, {
      center: [0, 0],
      zoom: 0,
      logo: false,
      extent: initExtent,
      showLabels: true,
    });
    this.map = map;
    window.map = map;

    //添加底图
    const basemapLayer = new ArcGISTiledMapServiceLayer(
      `http://10.87.94.143/OneMapServer/rest/services/shmap_as_dqy/MapServer`
    );
    basemapLayer.setScaleRange(1000000, 20001);

    map.addLayer(basemapLayer);

    const basemapLayer1 = new ArcGISTiledMapServiceLayer(
      `http://10.87.94.143/OneMapServer/rest/services/shmap_as3_19/MapServer`
    );
    basemapLayer1.setScaleRange(20000, 100);
    map.addLayer(basemapLayer1);

    //添加点图层
    const testpointLayer = await this.createGraphicLayer(testpoint);
    this.layers.testpointLayer = testpointLayer;

    const testpoint2Layer = await this.createGraphicLayer(testpoint2);
    this.layers.testpoint2Layer = testpoint2Layer;

    // const districtClusterLayer = await this.createGraphicLayer(districtCenter)
    // this.layers.districtClusterLayer = districtClusterLayer

    // const townClusterLayer = await this.createGraphicLayer(townCenter)
    // this.layers.townClusterLayer = townClusterLayer

    window.district = district;
    window.districtGraphicLayer = await this.createDistrictLayer(district);
    window.districtGraphicLayer.show();
    // const sfqDistrictGraphicLayer = await this.createSfqDistrictLayer(
    //   sfqDistrict
    // );
    // const subwayGraphicLayer = await this.createSubwayLayer(subway);

    // subwayGraphicLayer.on("load", (event) => {
    //   console.log("地铁图层加载完毕");
    // });

    window.overwriteGraphicLayer = new GraphicsLayer();
    this.map.addLayer(overwriteGraphicLayer);
    setTimeout(function () {
      this.map.graphics.hide();
    }, 2000);

    this.map.on("extent-change", (extS) => {
      let ext = extS.extent;
      if (
        ext.xmin < fullExtent.xmin ||
        ext.xmax > fullExtent.xmax ||
        ext.ymax > fullExtent.ymax ||
        ext.ymin < fullExtent.ymin
      ) {
        if (!window.lastMapExtent) {
          window.lastMapExtent = window.initExtent;
        }
        window.map.setExtent(window.lastMapExtent);
        console.log(ext);
      } else {
        window.lastMapExtent = extS.extent;
      }
    });
    window.shanghaiSpatialRef = this.map.spatialReference;
  },
  methods: {
    async createGraphicLayer(points) {
      const [
        GraphicsLayer,
        Graphic,
        Point,
        SimpleMarkerSymbol,
        SimpleRenderer,
        ClassBreaksRenderer,
        Color,
        InfoTemplate,
      ] = await jsapiUtil.load([
        "esri/layers/GraphicsLayer",
        "esri/graphic",
        "esri/geometry/Point",
        "esri/symbols/SimpleMarkerSymbol",
        "esri/renderers/SimpleRenderer",
        "esri/renderers/ClassBreaksRenderer",
        "esri/Color",
        "esri/InfoTemplate",
      ]);

      const graphicsLayer = new GraphicsLayer({
        visible: false,
      });

      const sms = new SimpleMarkerSymbol({
        color: [255, 0, 0, 150],
        size: 12,
        angle: 0,
        xoffset: 0,
        yoffset: 0,
        type: "esriSMS",
        style: "esriSMSCircle",
        outline: {
          color: [0, 0, 0, 255],
          width: 1,
          type: "esriSLS",
          style: "esriSLSSolid",
        },
      });

      points.forEach((item) => {
        const pt = new Point(
          Number(item.x),
          Number(item.y),
          this.map.spatialReference
        );

        const attr = {
          label: item.label,
          value: item.value,
        };
        const content = `<div>所需显示的内容</div>`;
        const infoTemplate = new InfoTemplate({
          title: "${label}",
          content: content,
        });
        const graphic = new Graphic(pt, null, attr, infoTemplate);
        graphicsLayer.add(graphic);
      });
      var renderer = new SimpleRenderer(sms);
      //颜色渐变
      renderer.setColorInfo({
        field: "value",
        minDataValue: 0,
        maxDataValue: 100,
        //渐变色
        // colors: [new Color([255, 255, 255]), new Color([127, 127, 0])],

        // //分段配色
        stops: [
          { value: 10, color: new Color([0, 0, 0, 0]) }, // -1 stddev
          { value: 39, color: new Color([0, 128, 64]) }, // average
          { value: 68, color: new Color([255, 0, 0, 0.8]) }, // 1 stddev
        ],
      });

      graphicsLayer.setRenderer(renderer);

      graphicsLayer.on("click", function (e) {
        console.log(e.graphic.attributes);
        const content = `<div>所需显示的内容123</div>`;
        const infoTemplate = new InfoTemplate({
          // title: "${label}",
          content: content,
        });
        e.graphic.infoTemplate = infoTemplate;
      });
      this.map.addLayer(graphicsLayer);

      return graphicsLayer;
    },
    showLayer() {
      this.layers.testpointLayer.show();
    },
    hideLayer() {
      this.layers.testpointLayer.hide();
    },
    showLayer2() {
      this.layers.testpoint2Layer.show();
    },
    hideLayer2() {
      this.layers.testpoint2Layer.hide();
    },
    hightlightByDistrictName(name) {
      this.hightlightByDistrictName(name);
    },
    async createDistrictLayer(data) {
      const [
        LabelClass,
        TextSymbol,
        SimpleLineSymbol,
        SimpleFillSymbol,
        PictureMarkerSymbol,
        SimpleRenderer,
        UniqueValueRenderer,
        GraphicsLayer,
        FeatureLayer,
        Graphic,
        Color,
        Point,
        Circle,
        InfoTemplate,
        Popup,
        PopupTemplate,
      ] = await jsapiUtil.load([
        "esri/layers/LabelClass",
        "esri/symbols/TextSymbol",
        "esri/symbols/SimpleLineSymbol",
        "esri/symbols/SimpleFillSymbol",
        "esri/symbols/PictureMarkerSymbol",
        "esri/renderers/SimpleRenderer",
        "esri/renderers/UniqueValueRenderer",
        "esri/layers/GraphicsLayer",
        "esri/layers/FeatureLayer",
        "esri/graphic",
        "esri/Color",
        "esri/geometry/Point",
        "esri/geometry/Circle",
        "esri/InfoTemplate",
        "esri/dijit/Popup",
        "esri/dijit/PopupTemplate",
      ]);

      const districtColor = [125, 125, 125, 0.35];
      // const districtOutlineColor = [255, 152, 0];
      const districtOutlineColor = [2, 134, 255];

      var featureCollection = {
        layerDefinition: null,
        featureSet: data,
      };

      var features = data.features;

      featureCollection.layerDefinition = {
        geometryType: data.geometryType,
        spatialReference: this.map.spatialReference,
        drawingInfo: {
          renderer: {
            type: "simple",
            symbol: {
              type: "esriSFS",
              style: "esriSFSSolid",
              color: districtColor,
              outline: {
                type: "esriSLS",
                style: "esriSLSSolid",
                color: districtOutlineColor,
                width: 2,
              },
            },
          },
        },
      };

      featureCollection.layerDefinition.fields = data.fields;

      var infoTemplate = {};

      const districtGraphicLayer = new FeatureLayer(featureCollection, {
        id: "districtGraphicLayer",
        spatialReference: this.map.spatialReference,
        // infoTemplate: template,
        // visible: true,
        visible: false,
      });

      const that = this;

      districtGraphicLayer.on("click", async function (e) {
        const content = `<div>所需显示的内容123456</div>`;
        const infoTemplate = new InfoTemplate({
          // title: "${label}",
          content: content,
        });
        e.graphic.infoTemplate = infoTemplate;
        const name = e.graphic.attributes.NAME;
        console.log(name);

        var sfs = new SimpleFillSymbol(
          SimpleFillSymbol.STYLE_SOLID,
          new SimpleLineSymbol(
            SimpleLineSymbol.STYLE_SOLID,
            new Color([120, 240, 120, 1]),
            3
          ),
          new Color([255, 0, 0, 0])
        );
        window.overwriteGraphicLayer.clear();
        window.overwriteGraphicLayer.add(new Graphic(e.graphic.geometry, sfs));

        await that.highlightDistrict(name, districtGraphicLayer);
      });

      this.map.addLayer(districtGraphicLayer);

      return districtGraphicLayer;
    },
    async hightlightByDistrictName(name) {
      const [
        Graphic,
        Geometry,
        Query,
        Color,
        Point,
        SimpleLineSymbol,
        SimpleFillSymbol,
        InfoTemplate,
        Popup,
        PopupTemplate,
        UniqueValueRenderer,
      ] = await jsapiUtil.load([
        "esri/graphic",
        "esri/geometry",
        "esri/tasks/query",
        "esri/Color",
        "esri/geometry/Point",

        "esri/symbols/SimpleLineSymbol",

        "esri/symbols/SimpleFillSymbol",
        "esri/InfoTemplate",
        "esri/dijit/Popup",
        "esri/dijit/PopupTemplate",
        "esri/renderers/UniqueValueRenderer",
      ]);

      var displayGeo = district.features.find((value, index, arr) => {
        return value.attributes.NAME == name;
      });

      var sfs = new SimpleFillSymbol(
        SimpleFillSymbol.STYLE_SOLID,
        new SimpleLineSymbol(
          SimpleLineSymbol.STYLE_SOLID,
          new Color([120, 240, 120, 1]),
          3
        ),
        new Color([255, 0, 0, 0])
      );
      map.infoWindow.setTitle("弹窗");
      map.infoWindow.setContent(`<div>所需显示的内容123456</div>`);
      var displayGraphic = new Graphic(displayGeo.geometry, sfs);
      var ct = displayGraphic.geometry.getExtent().getCenter();
      map.infoWindow.show(ct);

      window.overwriteGraphicLayer.clear();
      window.overwriteGraphicLayer.add(new Graphic(displayGeo.geometry, sfs));
      var uvrJson = {
        type: "uniqueValue",
        field1: "NAME",
        defaultSymbol: {
          color: [220, 255, 0, 164],
          outline: {
            color: [0, 255, 0, 255],
            width: 0,
            type: "esriSLS",
            style: "esriSLSSolid",
          },
          type: "esriSFS",
          style: "esriSFSSolid",
        },
        uniqueValueInfos: [
          {
            value: name,
            symbol: {
              color: [255, 0, 0, 128],
              outline: {
                color: [0, 255, 0, 0],
                width: 3,
                type: "esriSLS",
                style: "esriSLSSolid",
              },
              type: "esriSFS",
              style: "esriSFSSolid",
            },
          },
        ],
      };
      var renderer = new UniqueValueRenderer(uvrJson);
      districtGraphicLayer.setRenderer(renderer);
      districtGraphicLayer.redraw();
    },
    async createSfqDistrictLayer(data) {
      const [
        LabelClass,
        TextSymbol,
        SimpleLineSymbol,
        SimpleFillSymbol,
        PictureMarkerSymbol,
        SimpleRenderer,
        UniqueValueRenderer,
        GraphicsLayer,
        FeatureLayer,
        Graphic,
        Color,
        Point,
        Circle,
        InfoTemplate,
        Popup,
        PopupTemplate,
      ] = await jsapiUtil.load([
        "esri/layers/LabelClass",
        "esri/symbols/TextSymbol",
        "esri/symbols/SimpleLineSymbol",
        "esri/symbols/SimpleFillSymbol",
        "esri/symbols/PictureMarkerSymbol",
        "esri/renderers/SimpleRenderer",
        "esri/renderers/UniqueValueRenderer",
        "esri/layers/GraphicsLayer",
        "esri/layers/FeatureLayer",
        "esri/graphic",
        "esri/Color",
        "esri/geometry/Point",
        "esri/geometry/Circle",
        "esri/InfoTemplate",
        "esri/dijit/Popup",
        "esri/dijit/PopupTemplate",
      ]);
      var featureCollection = {
        layerDefinition: null,
        featureSet: data,
      };

      var features = data.features;

      featureCollection.layerDefinition = {
        geometryType: data.geometryType,
        spatialReference: this.map.spatialReference,
        drawingInfo: {
          renderer: {
            type: "simple",
            symbol: {
              color: [88, 156, 64, 50],
              outline: {
                color: [88, 156, 64, 255],
                width: 1,
                type: "esriSLS",
                style: "esriSLSSolid",
              },
              type: "esriSFS",
              style: "esriSFSSolid",
            },
          },
        },
      };

      featureCollection.layerDefinition.fields = data.fields;

      var infoTemplate = {};

      const sfqDistrictGraphicLayer = new FeatureLayer(featureCollection, {
        id: "sfqDistrictGraphicLayer",
        spatialReference: this.map.spatialReference,
        // infoTemplate: template,
        visible: true,
      });

      const that = this;

      this.map.addLayer(sfqDistrictGraphicLayer);

      return sfqDistrictGraphicLayer;
    },
    async highlightDistrict(name, districtGraphicLayer) {
      const [UniqueValueRenderer] = await jsapiUtil.load([
        "esri/renderers/UniqueValueRenderer",
      ]);
      var uvrJson = {
        type: "uniqueValue",
        field1: "NAME",
        defaultSymbol: {
          color: [220, 255, 0, 164],
          outline: {
            color: [0, 255, 0, 255],
            width: 0,
            type: "esriSLS",
            style: "esriSLSSolid",
          },
          type: "esriSFS",
          style: "esriSFSSolid",
        },
        uniqueValueInfos: [
          {
            value: name,
            symbol: {
              color: [255, 0, 0, 128],
              outline: {
                color: [0, 255, 0, 0],
                width: 3,
                type: "esriSLS",
                style: "esriSLSSolid",
              },
              type: "esriSFS",
              style: "esriSFSSolid",
            },
          },
        ],
      };
      var renderer = new UniqueValueRenderer(uvrJson);
      districtGraphicLayer.setRenderer(renderer);
      districtGraphicLayer.redraw();
      window.map.infoWindow.hide();
    },
    async createSubwayLayer(data) {
      const [
        LabelClass,
        TextSymbol,
        SimpleLineSymbol,
        SimpleFillSymbol,
        PictureMarkerSymbol,
        SimpleRenderer,
        UniqueValueRenderer,
        GraphicsLayer,
        FeatureLayer,
        Graphic,
        Color,
        Point,
        Circle,
        InfoTemplate,
        Popup,
        PopupTemplate,
      ] = await jsapiUtil.load([
        "esri/layers/LabelClass",
        "esri/symbols/TextSymbol",
        "esri/symbols/SimpleLineSymbol",
        "esri/symbols/SimpleFillSymbol",
        "esri/symbols/PictureMarkerSymbol",
        "esri/renderers/SimpleRenderer",
        "esri/renderers/UniqueValueRenderer",
        "esri/layers/GraphicsLayer",
        "esri/layers/FeatureLayer",
        "esri/graphic",
        "esri/Color",
        "esri/geometry/Point",
        "esri/geometry/Circle",
        "esri/InfoTemplate",
        "esri/dijit/Popup",
        "esri/dijit/PopupTemplate",
      ]);

      var featureCollection = {
        layerDefinition: null,
        featureSet: data,
      };

      var features = data.features;

      featureCollection.layerDefinition = {
        geometryType: data.geometryType,
        spatialReference: this.map.spatialReference,
        drawingInfo: {
          renderer: {
            type: "uniqueValue",
            field1: "NAME",
            defaultSymbol: {
              color: [255, 255, 255],
              width: 1,
              type: "esriSLS",
              style: "esriSLSSolid",
            },
            uniqueValueInfos: [
              {
                value: "轨道交通1号线",
                symbol: {
                  color: [255, 0, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "轨道交通2号线",
                symbol: {
                  color: [255, 0, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "轨道交通3号线",
                symbol: {
                  color: [255, 0, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "轨道交通4号线",
                symbol: {
                  color: [255, 0, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "轨道交通5号线",
                symbol: {
                  color: [255, 0, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "轨道交通6号线",
                symbol: {
                  color: [255, 0, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "轨道交通7号线",
                symbol: {
                  color: [255, 0, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "轨道交通8号线",
                symbol: {
                  color: [255, 0, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "轨道交通9号线",
                symbol: {
                  color: [255, 0, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "轨道交通10号线",
                symbol: {
                  color: [255, 0, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "轨道交通11号线",
                symbol: {
                  color: [255, 0, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "轨道交通12号线",
                symbol: {
                  color: [255, 0, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "轨道交通13号线",
                symbol: {
                  color: [255, 0, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "轨道交通16号线",
                symbol: {
                  color: [255, 140, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "轨道交通17号线",
                symbol: {
                  color: [255, 130, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "轨道交通浦江线",
                symbol: {
                  color: [255, 120, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
              {
                value: "磁浮",
                symbol: {
                  color: [255, 110, 0],
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
            ],
          },
        },
      };

      featureCollection.layerDefinition.fields = data.fields;

      var infoTemplate = {};

      const subwayGraphicLayer = new FeatureLayer(featureCollection, {
        id: "subwayGraphicLayer",
        spatialReference: this.map.spatialReference,
        visible: true,
      });

      this.map.addLayer(subwayGraphicLayer);

      return subwayGraphicLayer;
    },
    initDistrictClusterLayer() {
      this.createDistrictClusterLayer(testpoint2);
    },
    async createDistrictClusterLayer(pointArr) {
      const [
        LabelClass,
        TextSymbol,
        SimpleLineSymbol,
        SimpleMarkerSymbol,
        SimpleRenderer,
        Graphic,
        Color,
        Point,
      ] = await jsapiUtil.load([
        "esri/layers/LabelClass",
        "esri/symbols/TextSymbol",
        "esri/symbols/SimpleLineSymbol",
        "esri/symbols/SimpleMarkerSymbol",
        "esri/renderers/SimpleRenderer",
        "esri/graphic",
        "esri/Color",
        "esri/geometry/Point"
      ]);

      const qxPolygonGraphics = district.features;
      const centerXY = districtCenter;
      var clusterGraphics = [];
      pointArr.map((item) => {
        const pt =new Point(
          Number(item.x),
          Number(item.y),
          this.map.spatialReference
        );
        for (let i = 0; i < qxPolygonGraphics.length; i++) {
          const polygon = qxPolygonGraphics[i].geometry;
          if (polygon.contains(pt)) {
            centerXY[qxPolygonGraphics[i].attributes["NAME"]].count++;
            break;
          }
        }
      });
      for (var key in centerXY) {
        var x = centerXY[key].x;
        var y = centerXY[key].y;
        // var x = centerXY[key].x + (500 - Math.random() * 1000);
        // var y = centerXY[key].y + (500 - Math.random() * 1000);
        var qxpoint =new Point(
          Number(x),
          Number(y),
          this.map.spatialReference
        );
        let attributes = {
          行政区: key,
          类型: "区县",
          数量: centerXY[key].count,
        };
        var qxGraphic = new Graphic(qxpoint, {}, attributes, {});
        clusterGraphics.push(qxGraphic);
      }

      //聚合图圆的样式
      var lightgreen = new Color([76, 175, 80, 0.6]);
      var lightgreen2 = new Color([76, 175, 80]);
      var clusterSymbol = new SimpleMarkerSymbol(
        "solid",
        90,
        new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, lightgreen2, 0.8),
        lightgreen
      );
      var render = new SimpleRenderer(clusterSymbol);

      //聚合图标注样式
      var statesLabel = new TextSymbol().setColor(new Color("#fff"));
      statesLabel.font.setSize("12pt");
      statesLabel.font.setWeight(600);
      var labelClass = new LabelClass({
        labelExpressionInfo: {
          value: "{行政区}\n{数量}",
        },
        labelPlacement: "center-center",
      });
      labelClass.symbol = statesLabel;

      //聚合图
      const clusterLayer = await this.createFeatureLayer(clusterGraphics);
      clusterLayer.setRenderer(render);
      clusterLayer.setLabelingInfo([labelClass]);
      clusterLayer.setMaxScale(50001);
      clusterLayer.show();
      map.centerAndZoom(new Point(0, 0, window.shanghaiSpatialRef), 0);
      //散点图
      const clusterPointLayer = await this.initFeatureLayer(pointArr);
      clusterPointLayer.setMinScale(50000);
      clusterPointLayer.show();
    },
    async createFeatureLayer(features) {
      const [
        FeatureSet,
        FeatureLayer,
      ] = await jsapiUtil.load([
        "esri/tasks/FeatureSet",
        "esri/layers/FeatureLayer"
      ]);

      var dz = {
        displayFieldName: "",
        spatialReference: window.shanghaiSpatialRef,
      };

      const pointColor = [238, 69, 0, 144];
      const pointOutlineColor = [238, 69, 0, 180];
      const lineColor = [255, 152, 0];
      const polygonColor = [125, 125, 125, 0.35];
      const polygonOutlineColor = [2, 134, 255];

      if (features[0].geometry.hasOwnProperty("paths")) {
        dz.geometryType = "esriGeometryPolyline";
      } else if (features[0].geometry.hasOwnProperty("x")) {
        dz.geometryType = "esriGeometryPoint";
      } else if (features[0].geometry.hasOwnProperty("rings")) {
        dz.geometryType = "esriGeometryPolygon";
      }

      var attributes = features[0].attributes;
      var fields = [];
      var dzFeatures = [];

      var hasFID = false;

      for (var key in attributes) {
        if (key == "FID") {
          hasFID = true;
          var field = {
            name: key,
            type: "esriFieldTypeOID",
            alias: key,
          };
        } else {
          var field = {
            name: key,
            type: "esriFieldTypeString",
            alias: key,
          };
        }

        fields.push(field);
      }
      if (!hasFID) {
        var ofield = {
          name: "FID",
          type: "esriFieldTypeOID",
          alias: "FID",
        };

        fields.push(ofield);
      }

      var count = 1;

      features.map((item) => {
        if (!hasFID) {
          item.attributes.FID = count;
          count++;
        }

        var dzFeature = {
          attributes: item.attributes,
          geometry: item.geometry,
        };

        dzFeatures.push(dzFeature);
      });

      dz.fields = fields;
      dz.features = dzFeatures;

      var featureSet = new FeatureSet(dz);

      var featureCollection = {
        layerDefinition: null,
        featureSet: featureSet,
      };

      if (features[0].geometry.hasOwnProperty("paths")) {
        featureCollection.layerDefinition = {
          geometryType: dz.geometryType,
          spatialReference: window.shanghaiSpatialRef,
          drawingInfo: {
            renderer: {
              type: "simple",
              symbol: {
                color: lineColor,
                width: 2,
                type: "esriSLS",
                style: "esriSLSSolid",
              },
            },
          },
        };
      } else if (features[0].geometry.hasOwnProperty("x")) {
        featureCollection.layerDefinition = {
          geometryType: dz.geometryType,
          spatialReference: window.shanghaiSpatialRef,
          drawingInfo: {
            renderer: {
              type: "simple",
              symbol: {
                color: pointColor,
                size: 8,
                angle: 0,
                xoffset: 0,
                yoffset: 0,
                type: "esriSMS",
                style: "esriSMSCircle",
                outline: {
                  color: pointOutlineColor,
                  width: 1,
                  type: "esriSLS",
                  style: "esriSLSSolid",
                },
              },
            },
          },
        };
      } else if (features[0].geometry.hasOwnProperty("rings")) {
        featureCollection.layerDefinition = {
          geometryType: dz.geometryType,
          spatialReference: window.shanghaiSpatialRef,
          // "objectIdField": "ObjectID",
          drawingInfo: {
            renderer: {
              type: "simple",
              symbol: {
                type: "esriSFS",
                style: "esriSFSSolid",
                color: polygonColor,
                outline: {
                  type: "esriSLS",
                  style: "esriSLSSolid",
                  color: polygonOutlineColor,
                  width: 1,
                },
              },
            },
          },
        };
      }

      featureCollection.layerDefinition.fields = fields;

      var layer = new FeatureLayer(featureCollection, {
        spatialReference: window.shanghaiSpatialRef,
        infoTemplate: {},
        // visible: true,
        visible: false,
      });
      map.addLayer(layer);

      return layer;
    },
    async initFeatureLayer(points) {
      const [
        LabelClass,
        TextSymbol,
        Graphic,
        Color,
        Point
      ] = await jsapiUtil.load([
        "esri/layers/LabelClass",
        "esri/symbols/TextSymbol",
        "esri/graphic",
        "esri/Color",
        "esri/geometry/Point"
      ]);

      let graphicArr = [];
      points.forEach((item) => {
        const pt = new Point(
          Number(item.x),
          Number(item.y),
          this.map.spatialReference
        );
        const attr = {
          label: item.label,
          value: item.value,
        };
        const graphic = new Graphic(pt, null, attr, {});
        graphicArr.push(graphic);
      });

      //设置撒点标注的样式
      var statesLabel = new TextSymbol()
        .setColor(new Color("#fff"))
        .setHaloSize(1)
        .setHaloColor(new Color("#000"))
        .setOffset(0, 4);
      statesLabel.font.setSize("14pt");
      statesLabel.font.setWeight(600);
      var labelClass = new LabelClass({
        labelExpressionInfo: {
          value: `{label}`,
        },
        labelPlacement: "above-center",
      });
      labelClass.symbol = statesLabel;
      labelClass.minScale = 50001;

      const layer = await this.createFeatureLayer(graphicArr);
      layer.setLabelingInfo([labelClass]);
      console.log(layer);
      return layer;
    },
    async showFeatureLayer() {
      const testpoint2Layer1 = await this.initFeatureLayer(testpoint2);
      testpoint2Layer1.show();
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.map {
  height: 100%;
  width: 100%;
}
</style>
